<template>
	<view class="content">
		<view class="content_navbar">
			<u-navbar :title="utype == 1 ? conversation.nickname : conversation.detail" title-color="#101010"
				title-width="400" title-size="32" :border-bottom="false"></u-navbar>
			<view class="content_navbar_cell u-flex">
				<view @click="data.isPhone = true ">
					<u-image src="/pages/pagesMessage/static/phone.png" width="32" height="45" mode="widthFix"></u-image>
					<text>交换电话</text>
				</view>
				<view @click="data.isWechat = true">
					<u-image src="/pages/pagesMessage/static/wx.png" width="53" height="45" mode="widthFix"></u-image>
					<text>交换微信</text>
				</view>
				<!-- 企业用户 -->
				<view v-if="utype == 1" @click="$u.throttle(handleToInvitation, 1000)">
					<u-image src="/pages/pagesMessage/static/interview.png" width="38" height="45"
						mode="widthFix"></u-image>
					<text>面试邀请</text>
				</view>
				<view v-if="utype == 1" @click="$u.throttle(handleToResume, 1000)">
					<u-image src="/pages/pagesMessage/static/resume.png" width="38" height="45" mode="widthFix"></u-image>
					<text>查看简历</text>
				</view>
				<!-- 个人用户 -->
				<view v-if="utype == 2" @click="data.isResume = true">
					<u-image src="/pages/pagesMessage/static/resume.png" width="38" height="45" mode="widthFix"></u-image>
					<text>投递简历</text>
				</view>
				<view v-if="utype == 2" @click="$u.throttle(handleToCompany, 1000)">
					<u-image src="/pages/pagesMessage/static/company.png" width="51" height="45" mode="widthFix"></u-image>
					<text>查看企业</text>
				</view>
			</view>
		</view>
		<!-- 消息列表 -->
		<z-paging :paging-style="{paddingTop:data.top,paddingBottom:data.bottom}" ref="paging" v-model="messageList"
			use-chat-record-mode use-page-scroll :show-scrollbar="false" :auto-scroll-to-top-when-reload="false"
			:auto-clean-list-when-reload="false" @query="queryList">
			<view class="item" v-for="(item,index) in messageList" :key="item.messageid">
				<!-- 文字消息 -->
				<ItemText :itemText="item" v-if="item.type == 'text' || item.type == 'hello'"></ItemText>
				<!-- 系统消息 -->
				<ItemSystem :itemSystem="item" v-if="item.type == 'system'"></ItemSystem>
				<!-- 发送简历 -->
				<ItemResume :itemResume="item" v-if="item.type == 'resume'"></ItemResume>
				<!-- 发送职位 -->
				<ItemJob :itemJob="item" v-if="item.type == 'job'"></ItemJob>
				<!-- 企业邀请投递简历 -->
				<ItemInvite :itemInvite="item" :cid="conversation.cid" v-if="item.type == 'invite'"></ItemInvite>
				<!-- 位置 -->
				<ItemMap :itemMap="item" v-if="item.type == 'map'"></ItemMap>

				<!-- 交换手机号 -->
				<ItemMobile :itemMobile="item" :cid="conversation.cid" v-if="item.type == 'mobile'"></ItemMobile>
				<!-- 交换微信 -->
				<ItemWechat :itemWechat="item" :cid="conversation.cid" v-if="item.type == 'wechat'"
					@handleExchangeWechatAgree="handleWechatAgree"></ItemWechat>
			</view>
		</z-paging>

		<!-- 底部输入框 -->
		<u-message-fotter ref="messageInput" :utype="utype" :conversation="conversation" @initHeight="initHeight"
			:commonWordsMatch="data.commonWordsMatch"></u-message-fotter>

		<!-- 交换电话弹框 -->
		<u-modal v-model="data.isPhone" title="交换手机号" content="确认与对方交换电话吗？" show-cancel-button
			@cancel="data.isPhone = false" @confirm="handleExchangeMobile"></u-modal>
		<!-- 交换微信弹框 -->
		<u-modal v-model="data.isWechat" title="交换微信" show-cancel-button @cancel="data.isWechat = false"
			@confirm="handleOpenChangeWechat">
			<template v-slot:default>
				<view class="u-p-30">
					<u-input v-model="data.wechat" placeholder="请输入微信号"></u-input>
				</view>
			</template>
		</u-modal>
		<!-- 投递简历弹框 -->
		<u-modal v-model="data.isResume" title="投递简历" content="是否投递简历？" show-cancel-button
			@cancel="data.isResume = false" @confirm="handleOpenDelivery"></u-modal>
		<!-- 面试邀请 未下载简历弹框 -->
		<u-modal v-model="data.showInvite" title="系统提示" content="您需要下载简历才能发起发起面试邀请， 是否去简历详情下载简历？" show-cancel-button
			@cancel="data.showInvite = false" @confirm="handleToResume"></u-modal>
	</view>
</template>
<script setup>
	import {
		nextTick,
		reactive,
		ref,
		watch
	} from "vue";
	import {
		onReady,
		onLoad,
		onPageScroll,
		onShow
	} from '@dcloudio/uni-app'
	import {
		useUserIm
	} from '/stores/userIm.js'
	import useZPaging from "@/uni_modules/z-paging/components/z-paging/js/hooks/useZPaging.js";
	import ItemText from '@/components/message-elements/ItemText'
	import ItemSystem from '@/components/message-elements/ItemSystem'
	import ItemResume from '@/components/message-elements/ItemResume'
	import ItemJob from '@/components/message-elements/ItemJob'
	import ItemInvite from '@/components/message-elements/ItemInvite'
	import ItemMap from '@/components/message-elements/ItemMap'
	import ItemMobile from '@/components/message-elements/ItemMobile'
	import ItemWechat from '@/components/message-elements/ItemWechat'
	const Components = {
		ItemText,
		ItemSystem,
		ItemResume,
		ItemJob,
		ItemInvite,
		ItemMap,
		ItemMobile,
		ItemWechat
	}
	const IM = useUserIm()
	// 聊天对象信息
	const conversation = ref({})
	// 当前用户身份
	const utype = ref(0)
	const data = reactive({
		// 聊天对象ID
		chatId: '',
		// 交换手机弹框
		isPhone: false,
		// 交换微信弹框
		isWechat: false,
		wechat: '',
		// 同意交换微信数据
		WechatAgreeData: {},
		// 投递简历
		isResume: false,
		// 消息列表高度
		bottom: '',
		top: '',
		// 常用语列表
		commonWordsMatch: [],
		// 面试邀请未下载简历弹窗
		showInvite: false,
	})
	// 底部输入框
	const messageInput = ref(null)
	// pagingDOM
	const paging = ref(null)
	// 列表数据
	const messageList = ref([])
	onLoad(({
		item
	}) => {
		conversation.value = JSON.parse(item)
		data.chatId = JSON.parse(item).chat_id
		utype.value = uni.getStorageSync('utype')
		getUserCid()
	})
	onReady(() => {
		getListHeight()
	})
	onShow(() => {
		getPhraseList()
	})
	useZPaging(paging)
	watch(() => IM.messagelist, (nv) => {
		paging.value.reload()
	}, {
		deep: true
	})
	watch(() => messageList.value, (nv) => {
		sendReturnReceiptAll()
		mapMsgTime()
	}, {
		deep: true
	})
	// 获取对方用户cid
	const getUserCid = () => {
		uniCloud.callFunction({
			name: 'uni-store-cid',
			data: {
				uid: Number(conversation.value.relate_uid)
			}
		}).then(res => {
			if (res.result.data == 0) return
			if (res.result.data) {
				conversation.value.cid = res.result.data[0].cid
			} else {
				conversation.value.cid = 0
			}
		});
	}
	// 获取常用语列表
	const getPhraseList = async () => {
		let params = {
			token: IM.imToken
		}
		let res = await uni.$u.api.getPhraseList(params)
		if (res) data.commonWordsMatch = res.items
	}
	// 交换微信确定事件
	const handleWechatAgree = (itemWechat) => {
		data.isWechat = true
		data.WechatAgreeData = itemWechat
	}
	// 获取列表信息
	const queryList = async (pageNo, pageSize) => {
		let params = {
			token: IM.imToken,
			chat_id: conversation.value.chat_id,
			page: pageNo
		}
		let res = await uni.$u.api.getMessageList(params)
		paging.value.complete(res.items)
	}
	const mapMsgTime = () => {
		var date = new Date()
		var today = date.toLocaleDateString()
		var mark = []
		// 把消息按天分组
		messageList.value.forEach(element => {
			var item_date = uni.$u.timeFormat(element.addtime, 'yyyy/mm/dd') // 取出每个addtime的格式化日期
			if (Date.parse(item_date) == Date.parse(today)) {
				// 对比消息的时间戳和今天的时间戳，如果是相等的，放入标记（今天的每个日期都要赋值，后面要用来判断时间）
				mark.push(item_date)
				element.split_datetime = item_date
			} else {
				// 不是今天的消息，就按天分组
				if (mark.indexOf(item_date) == -1) {
					mark.push(item_date)
					element.split_datetime = item_date
				} else {
					element.split_datetime = ''
				}
			}
		})
		var last_time = 0
		// 细分处理每一天内的消息时间
		messageList.value.forEach(element => {
			// 分组日期不为空，代表需要在消息循环时显示时间
			if (element.split_datetime != '') {
				// 如果是今天，就细分，否则不处理
				if (Date.parse(element.split_datetime) == Date.parse(today)) {
					// 对比分组时间戳和今天的时间戳，是今天的消息才处理，否则不处理
					// 超过3分钟就独立标记
					var cha = (element.addtime - last_time) / 60
					if (cha > 3) {
						// 如果超过3分钟，就标记时分，否则把时间置空
						element.datetime = uni.$u.timeFormat(element.addtime, 'hh:MM')
					} else {
						element.datetime = ''
					}
					// 把本条消息的addtime记录下来，方便下次循环时对比
					last_time = element.addtime
				} else {
					element.datetime = element.split_datetime
				}
			}
		})
	}
	// input 输入时触发
	const initHeight = (height) => {
		if (height > 100) {
			data.bottom = height + 'px'
		} else {
			// #ifdef MP-WEIXIN
			data.bottom = 50 + uni.$u.sys().statusBarHeight + 'px'
			// #endif
			// #ifndef MP-WEIXIN
			data.bottom = '50px'
			// #endif
		}
	}
	// 关闭底部输入框显示
	const messageInputDisplayFlag = () => {
		messageInput.value.data.displayFlag = ''
	}
	/**
	 * 点开会话发送回执
	 */
	const sendReturnReceiptAll = () => {
		var msgObj = {
			controller: 'SendReturnReceipt',
			action: 'all',
			args: {
				token: IM.imToken,
				chatid: conversation.value.chat_id,
				cids: conversation.value.cid,
				title: uni.getStorageSync('userName')
			}
		}
		IM.webSocket_send(msgObj)
	}
	// 获取列表展示高度
	const getListHeight = async () => {
		let res = await uni.$u.getRect('.content_navbar');
		data.top = res.height + 'px'
		initHeight()
	}
	// 交换电话确认事件
	const handleExchangeMobile = () => {
		let msgObj = {
			controller: 'SendMobile',
			action: 'apply',
			args: {
				token: IM.imToken,
				chatid: data.chatId,
				cids: conversation.value.cid,
				content: '对方已确认交换手机号',
				title: uni.getStorageSync('userName')
			}
		}
		IM.webSocket_send(msgObj)
		messageInputDisplayFlag()
	}
	// 交换微信确认事件
	const handleOpenChangeWechat = () => {
		if (uni.$u.test.isEmpty(data.wechat)) {
			data.isWechat = true
			uni.$u.toast('请输入微信号')
			return
		}
		if (!uni.$u.test.wx(data.wechat) && !uni.$u.test.mobile(data.wechat)) {
			data.isWechat = true
			uni.$u.toast('您输入的微信号格式有误，请重新输入')
			return
		}
		if (!data.WechatAgreeData.messageid) {
			let msgObj = {
				controller: 'SendWechat',
				action: 'apply',
				args: {
					token: IM.imToken,
					chatid: data.chatId,
					wechat: data.wechat,
					cids: conversation.value.cid,
					content: '对方已确认交换微信号',
					title: uni.getStorageSync('userName')
				}
			}
			IM.webSocket_send(msgObj)
		} else {
			let msgObj = {
				controller: 'SendWechat',
				action: 'agree',
				args: {
					token: IM.imToken,
					messageid: data.WechatAgreeData.messageid,
					wechat: data.wechat,
					cids: conversation.value.cid,
					content: '对方已确认交换微信号',
					title: uni.getStorageSync('userName')
				}
			}
			IM.webSocket_send(msgObj)
		}
		data.wechat = ''
		messageInputDisplayFlag()
	}
	// 投递简历
	const handleOpenDelivery = async () => {
		let params = {
			jobid: conversation.value.jobid
		}
		let res = await uni.$u.api.getJobApplyAdd(params)
		uni.$u.toast('投递成功')
		messageInputDisplayFlag()
	}
	// 去公司详情页
	const handleToCompany = () => {
		uni.$u.route('pages/pagesHome/detailPages/company', {
			id: conversation.value.companyid,
			show: false
		})
		messageInputDisplayFlag()
	}
	// 去面试邀请页
	const handleToInvitation = async () => {
		// 判断企业是否认证 认证正常跳转 未认证跳转认证页面
		if (uni.getStorageSync('next_code') == 50004) return uni.$u.route('pages/pagesPersonal/set/auth/auth')
		let params = {
			resumeid: conversation.value.resumeid
		}
		let res = await uni.$u.api.getImResumeInfo(params)
		if (res.show_contact != 1) return data.showInvite = true
		uni.$u.route('/pages/pagesHome/detailPages/invitation', {
			resumeid: conversation.value.resumeid,
			fullname: conversation.value.nickname
		})
	}
	// 去简历详情页
	const handleToResume = () => {
		uni.$u.route('/pages/pagesHome/detailPages/resume', {
			id: conversation.value.resumeid,
			jobid: conversation.value.jobid,
			jobname: conversation.value.jobname
		})
	}
</script>
<style>
	page {
		background-color: #F6F6F6;
	}
</style>
<style lang="scss" scoped>
	.content {
		&_navbar {
			position: fixed;
			top: 0;
			width: 100vw;
			z-index: 999;

			&_cell {
				justify-content: space-between;
				padding: 26rpx 30rpx;
				background-color: #fff;

				view {
					display: flex;
					flex-direction: column;
					align-items: center;
					color: #8A8888;
					font-size: 26rpx;

					text {
						margin-top: 16rpx;
					}
				}
			}
		}
	}
</style>